import { Injectable } from "@nestjs/common";
import { CreateVideoDto } from "./dto/create-video.dto";
import { UpdateVideoDto } from "./dto/update-video.dto";
import { Core } from "src/core";
import { ObjectId } from "mongodb";
import { PaginationVideoDto } from "./dto/pagination-video.dto";
import axios from 'axios';
import { writeFile } from "fs";

const remote_host = "http://49.51.193.79:3000";

@Injectable()
export class VideoService {
    create(createVideoDto: CreateVideoDto) {
        return this.getCollection().insertOne({
            ...createVideoDto,
            createdAt: new Date(),
            updatedAt: new Date()
        });
    }

    async findAll(paginationVideoDto: PaginationVideoDto) {
        const param: any = {};
        if (paginationVideoDto.tag) {
            param.tags = { $in: [paginationVideoDto.tag] };
        }
        // console.log("param=====")
        // console.log(param)
        const limit = +paginationVideoDto.limit;
        const page = +paginationVideoDto.page;
        const total = await this.getCollection().countDocuments(param); // 获取总用户数
        const totalPages = Math.ceil(total / limit);
        const list = await this.getCollection().find(param).skip((page - 1) * limit).limit(limit).toArray();
        return { list, pagination: { totalPages, page, limit } };
    }

    async findOne(id: string) {
        const ary = await this.getCollection().findOne({ _id: new ObjectId(id) });
        return JSON.stringify(ary);
    }

    async update(id: string, updateVideoDto: UpdateVideoDto) {
        const filter = { _id: new ObjectId(id) };
        const update = { $set: { ...updateVideoDto, updatedAt: new Date() } };
        const result = await this.getCollection().updateOne(filter, update);
        return `Updated ${result.modifiedCount} document(s)`;
    }

    async remove(id: string) {
        const insertResult = await this.getCollection().deleteOne({ _id: new ObjectId(id) });
        return insertResult.deletedCount.toString();
    }

    getCollection() {
        return Core.ins.db.collection("video");
    }

    async downloadImg(param: any) {
        // const n = await download(img);
        // if (n) {
        //     const filter = { _id: new ObjectId(id) };
        //     const update = { $set: { img: n, updatedAt: new Date() } };
        //     const result = await this.getCollection().updateOne(filter, update);
        //     return `Updated ${result.modifiedCount} document(s)`;
        // }
        // return n;
        console.log("downloadImg", param);
        let suc = await post(remote_host + "/img", param);
        return suc;
    }

    async downloadVideo(param: any) {
        let suc = await post(remote_host + "/video/download", param);
        return suc;
    }
}


async function download(url) {
    try {
        const res = await axios.get(url, { responseType: 'arraybuffer' });
        const name = Date.now() + ".jpg";
        console.log("name", name)
        const suc = await saveFile("/root/www/proxy/images/" + name, res.data);
        if (suc) {
            return name;
        }
        return "";
    }
    catch (e) {
        console.log(e);
        return "0";
    }

}

function saveFile(name, data) {
    return new Promise(resolve => {
        writeFile(name, data, err => {
            if (err) {
                console.error(err);
                resolve(false);
                return;
            }
            resolve(true)

        });
    });
}

function post(url, param) {
    return new Promise(resolve => {
        // let URL = "http://49.51.69.50:3000/video/download";
        axios.post(url, param).then(res => {
            if (res.data.name) {
                resolve(true);
            } else {
                resolve(false);
            }
        }).catch(error => {
            resolve(false);
        });
        // fetch(url, {
        //     method: "POST",
        //     headers: {
        //         "Content-Type": "application/json"
        //     },
        //     body: JSON.stringify(param)
        // })
        //     .then(response => response.json())
        //     .then(res => {
        //         console.log(res);
        //         if (res.name) {
        //             resolve(true);
        //         } else {
        //             resolve(false);
        //         }
        //     })
        //     .catch(error => {
        //         resolve(false);
        //     });
    })

}
